<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>Scrapy学习（三） 爬取豆瓣图书信息 | 四畳半神话大系 | 圈地自萌</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="学习,Scrapy">
    <meta name="description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta property="og:type" content="article">
<meta property="og:title" content="Scrapy学习（三） 爬取豆瓣图书信息">
<meta property="og:url" content="http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/index.html">
<meta property="og:site_name" content="四畳半神话大系">
<meta property="og:description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta property="og:image" content="http://oi6538cys.bkt.clouddn.com/00douban.png">
<meta property="og:updated_time" content="2017-02-05T02:07:14.412Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scrapy学习（三） 爬取豆瓣图书信息">
<meta name="twitter:description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta name="twitter:image" content="http://oi6538cys.bkt.clouddn.com/00douban.png">
    
        <link rel="alternative" href="/atom.xml" title="四畳半神话大系" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.14">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/images/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">amoyiki</h5>
          <a href="mailto:amoyiki#gmail.com" title="amoyiki#gmail.com" class="mail">amoyiki#gmail.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/amoyiki" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-user-circle"></i>
                About
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Scrapy学习（三） 爬取豆瓣图书信息</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Scrapy学习（三） 爬取豆瓣图书信息</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-02-04T07:07:08.000Z" itemprop="datePublished" class="page-time">
  2017-02-04
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/Python/">Python</a></li></ul>

            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">前言</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#创建项目"><span class="post-toc-number">2.</span> <span class="post-toc-text">创建项目</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#编写Item"><span class="post-toc-number">3.</span> <span class="post-toc-text">编写Item</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#编写Spider"><span class="post-toc-number">4.</span> <span class="post-toc-text">编写Spider</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#突破反爬虫"><span class="post-toc-number">5.</span> <span class="post-toc-text">突破反爬虫</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#保存到MongoDB"><span class="post-toc-number">6.</span> <span class="post-toc-text">保存到MongoDB</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#其他"><span class="post-toc-number">7.</span> <span class="post-toc-text">其他</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-Scrapy学习（三）-爬取豆瓣图书信息"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Scrapy学习（三） 爬取豆瓣图书信息</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年02月04日 15:07" datetime="2017-02-04T07:07:08.000Z"  itemprop="datePublished">2017-02-04</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/Python/">Python</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><blockquote>
<ul>
<li><a href="http://www.amoyiki.com/2017/01/29/Scrapy%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89-%E5%AE%89%E8%A3%85/" target="_blank" rel="external">Scrapy学习（一） 安装</a></li>
<li><a href="http://www.amoyiki.com/2017/01/30/Scrapy%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89-%E5%85%A5%E9%97%A8/" target="_blank" rel="external">Scrapy学习（二） 入门</a></li>
</ul>
</blockquote>
<p>有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。<br><a id="more"></a><br>我的开发环境是 Win7 + PyChram + Python3.5 + MongoDB<br>爬虫的目标是豆瓣的日本文学标签下的所有书籍基本信息</p>
<h3 id="创建项目"><a href="#创建项目" class="headerlink" title="创建项目"></a>创建项目</h3><blockquote>
<p>scrapy startproject douban</p>
</blockquote>
<p>接着移动到<code>douban</code>目录下</p>
<blockquote>
<p>scrapy genspider book book.douban.com</p>
</blockquote>
<p>在spider目录下生成相应的BookSpider模板</p>
<h3 id="编写Item"><a href="#编写Item" class="headerlink" title="编写Item"></a>编写Item</h3><p>在items.py中编写我们需要的数据模型<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    book_name = scrapy.Field()</span><br><span class="line">    book_star = scrapy.Field()</span><br><span class="line">    book_pl = scrapy.Field()</span><br><span class="line">    book_author = scrapy.Field()</span><br><span class="line">    book_publish = scrapy.Field()</span><br><span class="line">    book_date = scrapy.Field()</span><br><span class="line">    book_price = scrapy.Field()</span><br></pre></td></tr></table></figure></p>
<h3 id="编写Spider"><a href="#编写Spider" class="headerlink" title="编写Spider"></a>编写Spider</h3><p>访问豆瓣的<a href="https://book.douban.com/tag/%E6%97%A5%E6%9C%AC%E6%96%87%E5%AD%A6?start=0" target="_blank" rel="external">日本文学</a>标签,将url的值写到<code>start_urls</code>中。接着在Chrome的帮助下，可以看到每本图书是在<code>ul#subject-list &gt; li.subject-item</code><br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="http://oi6538cys.bkt.clouddn.com/00douban.png" alt="日本文学" title="">
                </div>
                <div class="image-caption">日本文学</div>
            </figure><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookSpider</span><span class="params">(scrapy.Spider)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        sel = Selector(response)</span><br><span class="line">        book_list = sel.css(<span class="string">'#subject_list &gt; ul &gt; li'</span>)</span><br><span class="line">        <span class="keyword">for</span> book <span class="keyword">in</span> book_list:</span><br><span class="line">            item = BookItem()</span><br><span class="line">            item[<span class="string">'book_name'</span>] = book.xpath(<span class="string">'div[@class="info"]/h2/a/text()'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_star'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='rating_nums']/text()"</span>).extract()[</span><br><span class="line">                <span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_pl'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='pl']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            pub = book.xpath(<span class="string">'div[@class="info"]/div[@class="pub"]/text()'</span>).extract()[<span class="number">0</span>].strip().split(<span class="string">'/'</span>)</span><br><span class="line">            item[<span class="string">'book_price'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_date'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_publish'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_author'</span>] = <span class="string">'/'</span>.join(pub)</span><br><span class="line">            <span class="keyword">yield</span> item</span><br></pre></td></tr></table></figure></p>
<p>测试一下代码是否有问题</p>
<blockquote>
<p>scrapy crawl book -o items.json</p>
</blockquote>
<p>奇怪的发现，items.json内并没有数据，后头看控制台中的DEBUG信息</p>
<blockquote>
<p>2017-02-04 16:15:38 [scrapy.core.engine] INFO: Spider opened<br>2017-02-04 16:15:38 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)<br>2017-02-04 16:15:38 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023<br>2017-02-04 16:15:39 [scrapy.core.engine] DEBUG: Crawled (403) <get https:="" book.douban.com="" robots.txt=""> (referer: None)<br>2017-02-04 16:15:39 [scrapy.core.engine] DEBUG: Crawled (403) <get https:="" book.douban.com="" tag="" %e6%97%a5%e6%9c%ac%e6%96%87%e5%ad%a6?start="0"> (referer: None)</get></get></p>
</blockquote>
<p>爬取网页时状态码是403。这是因为服务器判断出爬虫程序，拒绝我们访问。<br>我们可以在settings中设定<code>USER_AGENT</code>的值，伪装成浏览器访问页面。</p>
<blockquote>
<p>USER_AGENT = “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”</p>
</blockquote>
<p>再试一次，就发现items.json有值了。但仔细只有第一页的数据，如果我们想要爬取所有的数据，就需要爬完当前页后自动获得下一页的url，以此类推爬完所有数据。<br>所以我们对spider进行改造。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">    sel = Selector(response)</span><br><span class="line">    book_list = sel.css(<span class="string">'#subject_list &gt; ul &gt; li'</span>)</span><br><span class="line">    <span class="keyword">for</span> book <span class="keyword">in</span> book_list:</span><br><span class="line">        item = BookItem()</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            item[<span class="string">'book_name'</span>] = book.xpath(<span class="string">'div[@class="info"]/h2/a/text()'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_star'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='rating_nums']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_pl'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='pl']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            pub = book.xpath(<span class="string">'div[@class="info"]/div[@class="pub"]/text()'</span>).extract()[<span class="number">0</span>].strip().split(<span class="string">'/'</span>)</span><br><span class="line">            item[<span class="string">'book_price'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_date'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_publish'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_author'</span>] = <span class="string">'/'</span>.join(pub)</span><br><span class="line">            <span class="keyword">yield</span> item</span><br><span class="line">        <span class="keyword">except</span>:</span><br><span class="line">            <span class="keyword">pass</span></span><br><span class="line">    nextPage = sel.xpath(<span class="string">'//div[@id="subject_list"]/div[@class="paginator"]/span[@class="next"]/a/@href'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">    <span class="keyword">if</span> nextPage:</span><br><span class="line">        next_url = <span class="string">'https://book.douban.com'</span>+nextPage</span><br><span class="line">        <span class="keyword">yield</span> scrapy.http.Request(next_url,callback=self.parse)</span><br></pre></td></tr></table></figure></p>
<p>其中<code>scrapy.http.Request</code>会回调parse函数，用try…catch是因为豆瓣图书并不是格式一致的。遇到有问题的数据，就抛弃不用。</p>
<h3 id="突破反爬虫"><a href="#突破反爬虫" class="headerlink" title="突破反爬虫"></a>突破反爬虫</h3><p>一般来说，如果爬虫速度过快。会导致网站拒绝我们的访问，所以我们需要在settings设置爬虫的间隔时间，并关掉COOKIES</p>
<blockquote>
<p>DOWNLOAD_DELAY = 2<br>COOKIES_ENABLED = False</p>
</blockquote>
<p>或者，我们可以设置不同的浏览器UA或者IP地址来回避网站的屏蔽<br>下面用更改UA来作为例子。<br>在middlewares.py,编写一个随机替换UA的中间件，每个request都会经过middleware。<br>其中<code>process_request</code>，返回<code>None</code>，Scrapy将继续到其他的middleware进行处理。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomUserAgent</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,agents)</span>:</span></span><br><span class="line">        self.agents = agents</span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">from_crawler</span><span class="params">(cls,crawler)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> cls(crawler.settings.getlist(<span class="string">'USER_AGENTS'</span>))</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self,request,spider)</span>:</span></span><br><span class="line">        request.headers.setdefault(<span class="string">'User-Agent'</span>,random.choice(self.agents))</span><br></pre></td></tr></table></figure></p>
<p>接着道<code>settings</code>中设置<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">DOWNLOADER_MIDDLEWARES = &#123;</span><br><span class="line">'douban.middlewares.RandomUserAgent': 1,</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line">USER_AGENTS = [</span><br><span class="line">    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",</span><br><span class="line">    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",</span><br><span class="line">    ...</span><br><span class="line">]</span><br></pre></td></tr></table></figure></p>
<p>再次运行程序，显然速度快了不少。</p>
<h3 id="保存到MongoDB"><a href="#保存到MongoDB" class="headerlink" title="保存到MongoDB"></a>保存到MongoDB</h3><p>接下来我们要将数据保存到数据库做持久化处理(这里用MongoDB举例，保存到其他数据库同理)。<br>这部分处理是写在<code>pipelines</code>中。在此之前我们还要先安装连接数据库的驱动。</p>
<blockquote>
<p>pip install pymongo</p>
</blockquote>
<p>我们在<code>settings</code>写下配置<br><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># MONGODB configure</span></span><br><span class="line"><span class="attr">MONGODB_SERVER</span> = <span class="string">'localhost'</span></span><br><span class="line"><span class="attr">MONGODB_PORT</span> = <span class="number">27017</span></span><br><span class="line"><span class="attr">MONGODB_DB</span> = <span class="string">'douban'</span></span><br><span class="line"><span class="attr">MONGODB_COLLECTION</span> = <span class="string">"book"</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MongoDBPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        connection = MongoClient(</span><br><span class="line">            host=settings[<span class="string">'MONGODB_SERVER'</span>],</span><br><span class="line">            port=settings[<span class="string">'MONGODB_PORT'</span>]</span><br><span class="line">        )</span><br><span class="line">        db = connection[settings[<span class="string">'MONGODB_DB'</span>]]</span><br><span class="line">        self.collection = db[settings[<span class="string">'MONGODB_COLLECTION'</span>]]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        self.collection.insert(dict(item))</span><br><span class="line">        log.msg(<span class="string">"Book  added to MongoDB database!"</span>,</span><br><span class="line">                level=log.DEBUG, spider=spider)</span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p>将运行项目的时候控制台中输出的DEBUG信息保存到log文件中。只需要在<code>settings</code>中设置</p>
<blockquote>
<p>LOG_FILE = “logs/book.log”</p>
</blockquote>
<p>项目代码地址：<a href="https://github.com/amoyiki/LearnedAndProTest/tree/master/douban" target="_blank" rel="external">豆瓣图书爬虫</a></p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-02-05T02:07:14.412Z" itemprop="dateUpdated">2017年2月5日 10:07</time>
</span><br>


        这里写留言或版权声明：<a href="/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" target="_blank" rel="external">http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/</a>
    </div>
    <footer>
        <a href="http://amoyiki.com">
            <img src="/images/avatar.jpg" alt="amoyiki">
            amoyiki
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Scrapy/">Scrapy</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/学习/">学习</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&title=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&pic=http://amoyiki.com/images/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&title=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&source=前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&via=http://amoyiki.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/02/13/Scrapy学习（四）-爬取微博数据/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Scrapy学习（四） 爬取微博数据</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/01/30/Scrapy学习（二）-入门/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Scrapy学习（二） 入门</h4>
      </a>
    </div>
  
</nav>



    




<section class="comments" id="comments">
    <div id="disqus_thread"></div>
    <script>
    var disqus_shortname = 'amoyiki';
    lazyScripts.push('//' + disqus_shortname + '.disqus.com/embed.js')
    </script>
    <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</section>




</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        

        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>四畳半神话大系 &copy; 2015 - 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&title=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&pic=http://amoyiki.com/images/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&title=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&source=前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Scrapy学习（三） 爬取豆瓣图书信息》 — 四畳半神话大系&url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/&via=http://amoyiki.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://amoyiki.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



</script>

<script src="/js/main.min.js?v=1.4.14"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.14" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
